package drds.global_transaction.transaction_coordinator;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import drds.common.ShouldNeverHappenException;

/**
 * 必须要从数据库进行获取,因为数据可以保存上次的ID,确保不会重复.
 */
public class TransactionIds
{

	private static AtomicLong transactionId = new AtomicLong(1000);
	// transactionIdInternal
	private static int transactionIdInternal = 200000000;

	public static long generateTransactionId()
	{
		long transactionIdValue = transactionId.incrementAndGet();
		if (transactionIdValue > transactionIdInternal)
		{
			synchronized (transactionId)
			{
				// updated by other thread
				if (transactionId.get() >= transactionIdValue)
				{
					transactionIdValue -= transactionIdInternal;
					transactionId.set(transactionIdValue);
				}
			}
		}
		return transactionIdValue;
	}

	public static void init(int serverNodeId)
	{
		try
		{
			transactionId.set(transactionIdInternal * serverNodeId);
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			Calendar calendar = Calendar.getInstance();
			Date date = simpleDateFormat.parse("2019-01-01");
			calendar.setTime(date);
			long base = calendar.getTimeInMillis();
			long current = System.currentTimeMillis();
			transactionId.addAndGet((current - base) / 1000);
		} catch (ParseException e)
		{
			throw new ShouldNeverHappenException(e);
		}
	}
}
